#!/usr/bin/env python3
#
#sklearn 中泰坦尼克号 kaggle 案例 
#
# 线性回归
#

import pandas
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import KFold   #<---这部分已经在2.0中被废弃掉，使用model_selection 代替cross_validation
'''
sklearn将在执行完后，提醒cross_validation将后续废弃掉。并提示使用model_selection替换，但不想不影响最后预测部分结果
'''
#from sklearn.model_selection import KFold  <--Kfold的的设变量改变了
import numpy as np

titanic = pandas.read_csv("train.csv")

#Age列讲缺失的补充，原有的数据均值进行填充
titanic["Age"] = titanic["Age"].fillna(titanic["Age"].median())

#print(titanic.head(3))
#查看这个字段下有哪几种 , 相似去重查询
#print(titanic['Sex'].unique())
#describe()讲可以实现到统计的效果
#print(titanic.describe())
#将来str 转成 int 
titanic.loc[titanic["Sex"] == "male","Sex"] = 0
titanic.loc[titanic["Sex"] == "female","Sex"] = 1
titanic["Embarked"] = titanic["Embarked"].fillna('S')
titanic.loc[titanic["Embarked"] == "S","Embarked"] = 0
titanic.loc[titanic["Embarked"] == "C","Embarked"] = 1
titanic.loc[titanic["Embarked"] == "Q","Embarked"] = 2

predictors = ["Pclass","Sex","Age","SibSp","Parch","Fare","Embarked"]

alg = LinearRegression()

#设定交叉验证的属性，如n_folds分为3倍
kf = KFold(titanic.shape[0] , n_folds = 3 , random_state = 1)

predictions = []

#循环训练与验证
for train , test in kf:
	#调取所需训练的数据（上方predictors的数据）
	##iloc---通过行号获取训练算法的(数据、结果)行数据
	train_predictiors = (titanic[predictors].iloc[train,:])
	#使用predictors、target训练算法
	train_target = titanic["Survived"].iloc[train]
	alg.fit(train_predictiors , train_target)
	#使用训练的算法对test进行预测
	test_predictions = alg.predict(titanic[predictors].iloc[test,:])
	#通过三组计算将其加入到 predictions中
	predictions.append(test_predictions)

predictions = np.concatenate(predictions , axis = 0)

predictions[predictions > .5] = 1
predictions[predictions <= .5] = 0

accuracy = len(predictions[predictions == titanic["Survived"]]) / len(predictions)

print("预测：",accuracy)